package org.koyad.portal.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.utils.UUIDGenerator;

/**
 * Acts as a front controller for ajax requests.
 * 
 * @author koyad
 */
@WebServlet(
	    name = "AjaxServlet", 
	    urlPatterns = {"/ajax"},
	    asyncSupported=true
)
public class AjaxServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().write(UUIDGenerator.generateUUID());
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageXML = req.getParameter("pageXML");
		Map map = (Map)req.getSession().getAttribute("3C690386ABA447D59284F469C348288B");
		String pageId = (String)map.get(FrameworkConstants.PISTON_PAGE_ID); 
		
		OutputStream os = null;
		try {
			os = new FileOutputStream(new File("D:/Tools/piston-pages/external/" + pageId + ".xml"));
			os.write(pageXML.getBytes());
		} catch (Exception e) {
			resp.getWriter().write("Exception occured");
		} finally {
			try {
				os.close();
			} catch (Exception e) {
				resp.getWriter().write("Exception occured");
			}
		}
		resp.getWriter().write("Page saved successfully");
	}
	
}
